import { BaseDatabase } from './base'
import {UserSettings} from "@/types";

const defaultSettings: UserSettings = {
  general: {
    autoUpdate: true,
    debugMode: false,
    language: 'zh-CN'
  },
  editor: {
    imageStoragePath: 'assets/images',
    defaultNoteType: 'markdown',
    notebookPath: '',  // 将在初始化时设置
    enableMultipleNotes: true,  // 默认允许多开
    maxOpenNotes: 10,          // 最多打开10个笔记
    wrapTabs: true,           // 默认标签换行
    autoSaveInterval: 60,     // 60秒自动保存
    maxHistoryCount: 50,      // 保留最近50条历史记录
    markdownConfig: {
      livePreview: true,
      codeHighlight: true
    }
  },
  sync: {
    enabled: false,
    type: 'none',
    serverUrl: ''
  },
  privacy: {
    fileEncryption: false,
    transmissionEncryption: true,
    timeoutProtection: false,
    timeoutDuration: 30
  },
  appearance: {
    theme: 'auto',
    fontSize: 14,
    fontFamily: 'system-ui',
    colors: {
      primary: '#409EFF',
      secondary: '#909399',
      success: '#67C23A',
      warning: '#E6A23C',
      danger: '#F56C6C',
      info: '#909399'
    },
    background: {
      type: 'color',
      value: '',
      opacity: 1
    }
  }
}
class SettingsDatabase extends BaseDatabase {

  public async init() {
    await this.createTable({
      name: 'settings',
      useJsonPath: true,
    })
    const res = await this.getSettings()
    if (!res) {
      const ress = await this.table?.insert(defaultSettings)
      if (!ress || !ress.success) {
        if (ress) {
          throw new Error(ress.error)
        }
      }
    }
  }

  async getSettings(): Promise<UserSettings | undefined>;
  async getSettings(path: string[]): Promise<any | undefined>;

  async getSettings(path?: string[]): Promise<any> {
    if (!path || path.length === 0) {
      const result = await this.table?.find()
      if (result?.success) {
        return result.data[0] as UserSettings | null
      }
      return undefined
    }
    const result = await this.table?.find()
    if (result?.success) {
      const settings = result.data[0] as UserSettings
      if (settings) {
        let val: any = settings;
        for (let string of path) {
          if (val === null || val === undefined) {
            return undefined;
          }

          // 如果是数字，当作数组索引处理
          const index = Number(string);
          if (!isNaN(index) && Array.isArray(val)) {
            val = val[index];
          } else {
            val = val[string];
          }
        }
        return val;
      }
    }
    return undefined
  }

  updateSettings(settings: Partial<UserSettings>): void {
    const current = this.getSettings() || defaultSettings
    this.table?.update([], {
      ...current,
      ...settings
    })
  }

  resetSettings(): void {
    this.table?.update([], defaultSettings)
  }
}

export const settingsDB = new SettingsDatabase()
